package com.book.realm;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.book.entity.Reader;
import com.book.mapper.ManagerMapper;

@Component
public class LoginRealm extends AuthorizingRealm {
  
	@Autowired
	private ManagerMapper managerMapper;

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) arg0;
		String username = token.getUsername();
		if(username.matches("\\d{10}")) {
			Reader reader = managerMapper.searchReader(username);
			if(reader==null) {
				throw new UnknownAccountException();
			}
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(reader.getUsername(),reader.getPassword(),"loginRealm");
		    return info;
		}
		if(username.matches("^(ad)\\d{6}")) {
			Reader reader = managerMapper.searchAdmin(username);
			if(reader==null) {
				throw new UnknownAccountException();
			}
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(reader.getUsername(),reader.getPassword(),"loginRealm");
		    return info;
		}
		return null;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		String username = (String) arg0.getPrimaryPrincipal();
		String role = managerMapper.selectUserRole(username);
		Set<String> userrole = new HashSet<String>();
		userrole.add(role);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRole(role);
		return info;
	}


}
